package cn.net.sinodata.system.msghandler.parse;


import cn.net.sinodata.common.core.enums.MsgParseHandlerTypeEnum;
import cn.net.sinodata.system.msghandler.parse.entitymapping.JsonEntityMapping;
import cn.net.sinodata.system.msghandler.parse.entitymapping.XmlEntityMapping;
import cn.net.sinodata.system.msghandler.exception.DynamicParseException;
import cn.net.sinodata.system.msghandler.parse.msgparse.JsonMessageParse;
import cn.net.sinodata.system.msghandler.parse.msgparse.XmlMessageParse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态解析工厂类
 */
@Slf4j
public class MsgParseFactory {

    private static final MsgParseFactory instance = new MsgParseFactory();

    private Map<MsgParseHandlerTypeEnum, MsgParseHandler> defaultHandlerMap = new HashMap<>();;

    private MsgParseFactory() {
        registryDefaultHandler();
    }

    /**
     * 注册默认的处理器
     */
    public void registryDefaultHandler() {
        defaultHandlerMap.put(MsgParseHandlerTypeEnum.XML, new MsgParseHandler(new XmlMessageParse(), new XmlEntityMapping()));
        defaultHandlerMap.put(MsgParseHandlerTypeEnum.JSON, new MsgParseHandler(new JsonMessageParse(), new JsonEntityMapping()));
        log.info("报文动态解析Handler加载完成");
    }

    /**
     * 工厂构建器
     * @return
     */
    public static MsgParseFactory build() {
        return instance;
    }

    /**
     * 通过msgType获取工厂中的handler
     * @param msgType 报文类型
     * @return
     * @throws Exception
     */
    public MsgParseHandler getHandler(MsgParseHandlerTypeEnum msgType) {
        return defaultHandlerMap.get(msgType);
    }

}
